package com.example.obtaingaode;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.annotation.Nullable;

import com.blankj.utilcode.util.TimeUtils;
import com.example.obtaingaode.activity.HomeActivity;
import com.example.obtaingaode.activity.MyApplication;
import com.example.obtaingaode.bean.CommonBean;
import com.example.obtaingaode.bean.UserInfomation;
import com.example.obtaingaode.db.LineEntrty;
import com.example.obtaingaode.db.LineEntrty_;
import com.example.obtaingaode.di.ActivityComponent;
import com.example.obtaingaode.di.DaggerActivityComponent;
import com.example.obtaingaode.net.MApi;
import com.example.obtaingaode.util.Constants;
import com.example.obtaingaode.util.HintUtil;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.inject.Inject;

import frame.m.com.mylibrary.http.BaseResult;
import frame.m.com.mylibrary.http.HttpConstant;
import frame.m.com.mylibrary.http.ProgressSubscriber;
import io.objectbox.Box;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * 线路录入的服务
 * Created by Ma.Chong on 2017/10/15.
 */

public class LineServer extends Service {
    private static String location;
    private SendCallback callback = null;
    private Timer timer;

    public void setCallback(SendCallback callback) {
        this.callback = callback;
    }

    public SendCallback getCallback() {
        return callback;
    }

    @Inject
    public MApi mApi;
    @Inject
    Box<LineEntrty> lineEntrtyBox;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        DaggerActivityComponent.builder().appComponent(MyApplication.getAppComponent()).build()
                .inject(this);
        startUploadLine();
        return new Binder();
    }

    @Override
    public void unbindService(ServiceConnection conn) {
        super.unbindService(conn);
        timer.cancel();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        timer.cancel();
        Logger.d("轨迹记录结束");
        return super.onUnbind(intent);
    }

    /**
     * 上传轨迹信息
     */
    private void startUploadLine() {
        AlarmTask timeTask = new AlarmTask();
        timer = new Timer();
        timer.schedule(timeTask, 1000, 5* 1000);
        AlarmTask2 timeTask2=new AlarmTask2();
        Timer timer2 = new Timer();
        timer2.schedule(timeTask2,1000,2*1000);
    }

    public class AlarmTask extends TimerTask {
        @Override
        public void run() {
            callback.getLocation();
        }
    }

    /**
     * 在息屏状态下,每隔2秒更新位置信息
     */
    public class AlarmTask2 extends  TimerTask{
        @Override
        public void run() {
            PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
                if (!pm.isInteractive()){
                    callback.changeLocation();
                }
            }else{
                if (!pm.isScreenOn()){
                    callback.changeLocation();
                }
            }
        }
    }



    public class Binder extends android.os.Binder {
        public void setLocation(String location) {
            LineServer.location = location;
            requestUploadLocation(LineServer.location);
        }

        public LineServer getLineServere() {
            return LineServer.this;
        }

    }

    private void requestUploadLocation(String location) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("actionName", Constants.URL_SAVE);
        map.put("positionData", location);
        map.put("deviceType", "point_navigation");
        map.put("deviceNo", new Date().getTime()+"");
        map.put("remark", "-1");
        map.put("userNo", UserInfomation.getUserNo());
        String url = String.format("%s?para=%s", Constants.getBaseUrl(), new Gson()
                .toJson(map).toString());
        Logger.d("请求的数据是url>>>" + url);
        final Long id= saveLineDataDb(map);
        Observable<BaseResult<String>> ob = mApi
                .save(url);
        ob.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new DisposableObserver<BaseResult<String>>() {
            @Override
            public void onNext(@NonNull BaseResult<String> commonBeanBaseResult) {
                if(commonBeanBaseResult.isSuccess()){
                    Logger.d("%s的数据上传成功!",id);
                    setUploadTrueById(id);
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {

            }

            @Override
            public void onComplete() {
                Logger.d("%s的数据上传成功!",id);
            }
        });

    }

    /**
     * 根据id更改数据库里面的isUoload标签为true
     * @param id
     */
    private void setUploadTrueById(Long id) {
        List<LineEntrty> lineEntrties = lineEntrtyBox.find(LineEntrty_.id, id);
        if(lineEntrties.isEmpty())
        {
            return;
        }
        LineEntrty lineEntrty = lineEntrties.get(0);
        lineEntrty.setIsUpload(true);
        long changeId = lineEntrtyBox.put(lineEntrty);
        Logger.d("id为%s的数据更改上传状态为true",""+changeId);
    }

    /**
     * 本地数据库存入数据
     *
     * @param map
     */
    private long saveLineDataDb(Map<String, String> map) {
        LineEntrty entnty = new LineEntrty(0L, map.get("positionData"), "" + new Date().getTime()
                , TimeUtils.millis2String(new Date().getTime(), new SimpleDateFormat
                ("yyyy-MM-dd")), false, map.get("userNo"), map.get("deviceType"));
       return lineEntrtyBox.put(entnty);
    }

    public static interface SendCallback {
        public void getLocation();
        public void saveLineSuccess();
        public void changeLocation();
    }
}
